//
//  HomeStatusViewModel.swift
//  微博
//
//  Created by admin on 2018/3/27.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit

class HomeStatusViewModel {
    //认证图片
    var verifiedImage: UIImage?
    //会员等级
    var mbrankImage: UIImage?
    //微博时间
    var createdAtText: String? {
        return dealSinaTime(created_at: status?.created_at)
    }
    //微博来源
    var sourceText: String?
    
    var retweeteBtnStr:String?//转发按钮现实的文字
    var commentBtnStr:String?//评论按钮显示的文字
    var likeBtnStr:String?//点赞按钮现实的文字
    var retweetedContentStr:String?//被转发微博文字
    var statusPictureViewSize:CGSize=CGSize()//配图视图大小
    
    var status:HomeStatusModel?{
        didSet{
            //认证
            verifiedImage = dealVerifiedImage(verified: status?.user?.verified ?? -1)
            //会员等级
            mbrankImage = dealMbrankImage(mbrank: status?.user?.mbrank ?? 0)
            //微博来源
            sourceText = dealSinaSource(source: status?.source)
            
            retweeteBtnStr = countString(count: (status?.reposts_count)!, defaultStr: "转发")
            commentBtnStr = countString(count: (status?.comments_count)!, defaultStr: "评论")
            likeBtnStr = countString(count: (status?.attitudes_count)!, defaultStr: "点赞")
            //计算行高
            statusPictureViewSize = calcPictureViewSize(count: picModelList?.count)
            
            retweetedContentStr = "@" + (status?.retweeted_status?.user?.name ?? "")
            retweetedContentStr? += ": " + (status?.retweeted_status?.text ?? "")
            
        }
    }
    
    /// 计算行属性，取被转发微博配图，没有就取原创的
    var picModelList:[StatusPictureModel]? {
        return status?.retweeted_status?.pic_urls ?? status?.pic_urls
    }
    
}

extension HomeStatusViewModel {
    
    //用户认证图片
    fileprivate func dealVerifiedImage(verified: Int) -> UIImage?{
        
        //图片名称
        var imgName = ""
        switch verified {
        case 1:
            imgName = "avatar_vip"
        case 2,3,5:
            imgName = "avatar_enterprise_vip"
        case 220:
            imgName = "avatar_grassroot"
        default:
            imgName = "avatar_vgirl"
        }
        return UIImage(named: imgName)
        
    }
    
    //会员等级 1-6
    fileprivate func dealMbrankImage(mbrank: Int) -> UIImage?{
        if mbrank >= 1 && mbrank <= 6 {
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        return UIImage(named: "common_icon_membership")
    }
    
    
    /// 转发、评论、点赞数字处理
    ///
    /// - Parameters:
    ///   - count: 数字
    ///   - defaultStr: 默认描述
    /// - Returns: 返回 处理后的字符串
    fileprivate func countString(count: Int64,defaultStr: String) -> String {
        if count==0{
            return defaultStr
        } 
        if count<10000 {
            return count.description
        }else{//大于1万的
            return String(format: "%.02f 万", count/10000)
        }
        
    }
    
    /// 计算配图视图大小
    ///
    /// - Parameter count: 配图数量
    /// - Returns: 返回配图视图大小
    fileprivate func calcPictureViewSize(count:Int?) ->CGSize {
        guard let count = count else {
            return CGSize()
        }  
        //计算行数
        let row=(count - 1) / 3 + 1
        //总高度
        var statusPictureViewHeight = statusPictureViewOutMargin
            statusPictureViewHeight += statusPictureItemWith * CGFloat(row)
            statusPictureViewHeight += CGFloat((row - 1 )) * CGFloat(statusPictureViewinMargin) 
        return CGSize(width: statusPcitureViewWith, height: statusPictureViewHeight)
    }
    
    /// 单张配图时计算配图视图大小
    ///
    /// - Parameter image: 图片
    func calcSinglePictureViewSize(image:UIImage) {
        //图片大小
        statusPictureViewSize = image.size
    }
    
}

//处理微博时间
extension HomeStatusViewModel {
    
    fileprivate func dealSinaTime(created_at: Date?) -> String?{
        //判断是否为nil
        guard let d = created_at else {
            
            return nil
        }
        
        //定义时间格式化
        let df = DateFormatter()
        //定义日期格式字符串
        let dateFormatString: String
        //判断是否是今年
        if isThisYear(sinaDate: d) {
            //日历类
            let calender = Calendar.current
            //如果是今天
            if calender.isDateInToday(d) {
                //计算发布微博日期和当前日期比较差值
                let s = Int(-d.timeIntervalSinceNow)
                //显示刚刚
                if s < 60 {
                    return "刚刚"
                } else if s >= 60 && s < 3600 {
                    return "\(s/60)分钟前"
                } else {
                    return "\(s/3600)小时前"
                }
                
            } else if calender.isDateInYesterday(d) {
                //昨天
                dateFormatString = "昨天 HH:mm"
            } else {
                //05月21日 12:32
                dateFormatString = "MM月dd日 HH:mm"
            }
        } else {
            //2015年05月21日 12:32
            dateFormatString = "yyyy年MM月dd日 HH:mm"
        }
        
        //指定格式
        df.dateFormat = dateFormatString
        //返回
        return df.string(from: d)
    }
    
    //判断是否是今年
    fileprivate func isThisYear(sinaDate: Date) -> Bool{
        
        //定义时间格式化
        let df = DateFormatter()
        //指定格式
        df.dateFormat = "yyyy"
        //拿到系统时间
        let currentDate = Date()
        //通过日期拿到要用的字符串
        let sinaString = df.string(from: sinaDate)
        //当前时间
        let currentString = df.string(from: currentDate)
        return sinaString == currentString
        
    }
}

//处理微博来源
extension HomeStatusViewModel{
    
    fileprivate func dealSinaSource(source: String?) -> String?{
        //判断是否为nil 且是否保存
        guard let s = source, s.contains("\">") else {
            return "来自 Smartisan T3"
        }
        //截取字符
        let startIndex = s.range(of: "\">")!
        let endIndex = s.range(of: "</")
        //
        let resualt = s.substring(with: startIndex.upperBound..<(endIndex?.lowerBound)!)
        return "来自" + resualt
        
    }
}
